const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HappyPack = require('happypack');
const os = require('os');
const happyThreadPool = HappyPack.ThreadPool({ size : os.cpus().length });
const resolve = dir => path.join(__dirname, dir);

const base = {
	resolve : {
		extensions : ['.js', '.jsx', '.css', '.scss'],
		alias : {
			'@' : resolve('src')
		}
	},
	module : {
		rules : [
			{
				test : /\.(js|jsx)$/,
				loader : 'happypack/loader?id=happyBabel',
				exclude : /node_modules/
			},
			{
				test : /\.(png|jpe?g|gif|svg)(\?.*)?$/,
				exclude : /node_modules/,
				use : [
					{
						loader : 'url-loader?cacheDirectory=true',
						options : {
							limit : 10000,
							name : 'img/[name].[hash:8].[ext]'
						}
					},
					'img-loader'
				]
			},
			{
				test : /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
				loader : 'happypack/loader?id=happyVideo',
				exclude : /node_modules/,
				options : {
					limit : 10000,
					name : 'media/[name].[hash:8].[ext]'
				}
			},
			{
				test : /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
				loader : 'happypack/loader?id=happyFont',
				exclude : /node_modules/,
				options : {
					limit : 10000,
					name : 'fonts/[name].[hash:8].[ext]'
				}
			}
		]
	},
	plugins : [
		new HappyPack({
			id : 'happyBabel',
			loaders : [{
				loader : 'babel-loader?cacheDirectory=true'
			}],
			threadPool : happyThreadPool,
			verbose : true
		}),
		new HappyPack({
			id : 'happyVideo',
			loaders : [{
				loader : 'url-loader?cacheDirectory=true'
			}],
			threadPool : happyThreadPool,
			verbose : true
		}),
		new HappyPack({
			id : 'happyFont',
			loaders : [{
				loader : 'url-loader?cacheDirectory=true'
			}],
			threadPool : happyThreadPool,
			verbose : true
		}),
		new MiniCssExtractPlugin({
			filename : 'css/[name].[chunkhash:8].css'
		}),
		new webpack.DefinePlugin({
			'process.env' : {
				NODE_ENV : JSON.stringify(process.env.NODE_ENV)
			}
		})
	]
};
if (process.env.NODE_ENV === 'development') {
	base.module.rules.push({
		test : /\.scss|.css$/,
		use : [
			'style-loader',
			{ loader : 'css-loader', options : { importLoaders : 3 } }, // 导入的sass加上前缀兼容
			'sass-loader',
			{
				loader : 'sass-resources-loader',
				options : {
					resources : [resolve('src/assets/css/variables.scss')]
				}
			},
			'postcss-loader'
		]
	});
} else {
	base.module.rules.push(
		{
			test : /\.css$/,
			use : [
				MiniCssExtractPlugin.loader,
				'css-loader',
				{
					loader : 'postcss-loader'
				}
			]
		},
		{
			test : /\.scss$/,
			use : [
				MiniCssExtractPlugin.loader,
				{ loader : 'css-loader', options : { importLoaders : 3 } },
				'sass-loader',
				{
					loader : 'sass-resources-loader',
					options : {
						resources : [resolve('src/assets/css/variables.scss')]
					}
				},
				'postcss-loader'
			]
		}
	);
}
module.exports = base;
